package com.heima.behavior.Interceptor;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.AdminThreadUtil;
import com.heima.utils.thread.ApThreadLocalUtil;
import io.jsonwebtoken.Claims;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class BehaviorInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        try {
            //解析token
            Claims claims = AppJwtUtil.getClaimsBody(token);
            int res = AppJwtUtil.verifyToken(claims);
            if (res == 1 || res == 2) {
                //token过期
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                return false;
            }
            //获取id
            Integer userId = (Integer) claims.get("id");
            //把id存入线程中
            ApThreadLocalUtil.set(userId);
        } catch (Exception e) {
            //捕获异常也是禁止介入
            e.printStackTrace();
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return false;
        }
        return HandlerInterceptor.super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AdminThreadUtil.clear();
    }
}
